package com.yungu.swift.order.utils;

import com.yungu.swift.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import static com.yungu.swift.order.config.NacosListener.ALIPAY_CONFIG;

/**
 * Created by cuixiuyinin on 2018/4/24.
 */
public class PaySignBuilder {

    static String signRSA(String url, String key) {
        if (ALIPAY_CONFIG.getAlipaySignTypeRsa2()) {
            String sign = RSASignature.sign(url, key);
            if (StringUtils.isNotBlank(sign)) {
                try {
                    return URLEncoder.encode(sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return null;
        } else {
            try {
                String sign = RSASignature.sign(url, key);
                if (sign != null) {
                    return URLEncoder.encode(sign, "UTF-8");
                }
                return "";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return "";
        }
    }


    static String signMD5(Map<String, String> map, String key) {
        String url;
        if (ALIPAY_CONFIG.getAlipaySignTypeRsa2()) {
            url = PayUrlBuilder.buildUrl(map, false, false, false);
        } else {
            url = PayUrlBuilder.buildUrl(map, false);
        }
        return Md5Utils.encode(url + "&key=" + key).toUpperCase();
    }

    public static String wxSignMD5(Map<String, String> map, String key) {
        String url = PayUrlBuilder.buildUrl(map, false);
        return Md5Utils.encode(url + "&key=" + key).toUpperCase();
    }

    static String wxSignMD5(Map<String, String> map, String key, String charset) {
        String url = PayUrlBuilder.buildUrl(map, false);
        return Md5Utils.encode(url + "&key=" + key, charset).toUpperCase();
    }
}
